package com.xgkj.diyiketang.activity.data;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.AdvertiseInfo;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.ViewUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by steveqi on 2017/4/21.
 * Email: cnjiaqi@sina.com
 */

public class RecommPicAdapter extends BaseAdapter {
    private final Context mContext;
    private List<AdvertiseInfo> mList = new ArrayList<AdvertiseInfo>();

    public RecommPicAdapter(Context context) {
        this.mContext = context;
    }

    public void updateData(List<AdvertiseInfo> picList) {
        if (picList != null) {
            mList.addAll(picList);
        }
        notifyDataSetChanged();
    }

    public void clearData() {
        if (mList != null) {
            mList.clear();
        }
    }

    @Override
    public int getCount() {
        if (mList != null && mList.size() > 0) {
            return mList.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (mList != null && mList.size() > 0) {
            mList.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ChildHolder holder = null;
        if (holder == null) {
            holder = new ChildHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.pic_item, null);
            holder.img = (ImageView) convertView.findViewById(R.id.img_item);
            convertView.setTag(holder);
        } else {
            holder = (ChildHolder) convertView.getTag();
        }
        AdvertiseInfo info = mList.get(position);
        String picIconUrl = info.getUrl();
        if (picIconUrl != null && picIconUrl.length() > 0) {
            Bitmap cacheBitmap = ImageCache.getInstance(mContext).getBitmapFromMemoryCache(picIconUrl);
            if (cacheBitmap != null) {
                holder.img.setImageBitmap(cacheBitmap);
            } else {
                holder.img.setImageResource(R.drawable.zhanweitu);
                ImageCache.getInstance(mContext).loadBitmapToView(holder.img, picIconUrl, new ViewUtil.Size(ViewUtil.dip2px(mContext, 170), ViewUtil.dip2px(mContext, 170)));
            }
        }
        return convertView;
    }

    class ChildHolder {
        ImageView img;
    }
}
